const errorType = require('../constant/errorType')
const service = require('../service/user.service')
const _md5 = require('../utils/_md5')
const userVerify = async (ctx, next) => {
  const { user, password } = ctx.request.body
  // 用户名或者密码不能为空
  if (!user || !password) {
    // 发送错误
    return ctx.app.emit('error', new Error(errorType.USER_OR_PASSWORD_CAN_NOT_BE_EMPTY), ctx)
  }
  // 用户名不能被注册过
  const result = await service.getUserByName(user)
  if (result.length !== 0) {
    return ctx.app.emit('error', new Error(errorType.USER_ALREADY_EXISTS), ctx)
  }
  // 验证通过
  await next()
}

const passwordHandle = async (ctx, next) => {
  const { password } = ctx.request.body
  ctx.request.body.password = _md5(password)
  await next()
}

const loginVerify = async (ctx, next) => {
  const { user, password } = ctx.request.body
  // 用户名或者密码不能为空
  if (!user || !password) {
    // 发送错误
    return ctx.app.emit('error', new Error(errorType.USER_OR_PASSWORD_CAN_NOT_BE_EMPTY), ctx)
  }
  // 用户名必须存在
  const result = await service.getUserByName(user)
  if (result.length === 0) {
    return ctx.app.emit('error', new Error(errorType.USER_NOT_EXISTS), ctx)
  }
  // 验证通过
  await next()
}

const passwordVerify = async (ctx, next) => {
  const { user, password } = ctx.request.body
  const result = await service.getUserByName(user)
  if (result[0].password !== password) {
    return ctx.app.emit('error', new Error(errorType.PASSWORD_IS_INCORRECT), ctx)
  }
  ctx.user = result[0]
  await next()
}

module.exports = {
  userVerify,
  passwordHandle,
  loginVerify,
  passwordVerify
}